package org.koyabr.webx.demo.danmaku.web.ajax.module.screen;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.citrus.turbine.Context;

import org.koyabr.webx.demo.danmaku.web.common.util.ListTool;
import org.koyabr.webx.demo.danmaku.biz.PostManager;
import org.koyabr.webx.demo.danmaku.biz.UserManager;
import org.koyabr.webx.demo.danmaku.dal.dataobjs.Post;
import org.koyabr.webx.demo.danmaku.dal.dataobjs.User;
import org.koyabr.webx.demo.danmaku.web.common.DanmakuUser;
import org.springframework.beans.factory.annotation.Autowired;

public class TabPanel {
	@Autowired
	private PostManager postManager;

	@Autowired
	private UserManager userManager;

	@Autowired
	private HttpServletRequest request;

	public void execute(Context context) throws Exception {

		String username = DanmakuUser.getCurrentUser().getUsername();
		User currentUser = userManager.getUser(username);

		List<List<Post>> pageList, hotList, freshList;

		String sortSeed = request.getParameter("sort").toLowerCase();
		String category = request.getParameter("category").toLowerCase();
		String personal = request.getParameter("personal").toLowerCase();

		if (sortSeed == null
				|| (!sortSeed.equals("date") && !sortSeed.equals("title"))) {
			sortSeed = "date";
		}
		if (category == null
				|| (!category.equals("tv") && !category.equals("game")
						&& !category.equals("cartoon")
						&& !category.equals("course") && !category
							.equals("favor"))) {
			category = null;
		}

		/*浏览主页内容，显示热门列表和新鲜列表*/
		if (category == null) {
			if ("true".equals(personal)) {
				hotList = ListTool.splitList(postManager
						.getAllPostsByAuthor(username, "playNum", "desc"), 6);
				freshList = ListTool.splitList( postManager
						.getAllPostsByAuthor(username, "date", "desc"), 6);
			}
			else {
				hotList = ListTool.splitList( postManager
						.getAllPosts( "playNum", "desc"), 6);
				freshList = ListTool.splitList( postManager
						.getAllPosts( "date", "desc"), 6);
			}
			
			context.put("hotList", hotList);
			context.put("freshList", freshList);
		}
		/*浏览某个分类的内容*/
		else {
			if("favor".equals(category)) {
				pageList = ListTool.splitList(currentUser.favorSet.toList(), 9);
			}
			else if("true".equals(personal)) {
				pageList = ListTool.splitList( postManager
						.getAllPostsByAutAndCat( username, category, sortSeed, "desc"), 9);
			}
			else {
				pageList = ListTool.splitList( postManager
						.getAllPostsByCategory( category, sortSeed, "desc"), 9);
			}
			
			context.put("pageList", pageList);
		}

	}
}
